using MediatR;
using MeetingManagement.Domain.Entities;
using MeetingManagement.Domain.Repositories;

namespace MeetingManagement.Application.Commands.Users.CreateUser;

public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, bool>
{
    private readonly IRepository<User> _userRepository;
    public CreateUserCommandHandler(IRepository<User> userRepository)
    {
        _userRepository = userRepository;
    }

    public async Task<bool> Handle(CreateUserCommand request, CancellationToken cancellationToken)
    {
        bool emailExists = _userRepository.Query().Any(u => u.Email == request.Email);
        if (emailExists) return false;

        bool usernameExists = _userRepository.Query().Any(u => u.Username == request.UserName);
        if (usernameExists) return false;

        var user = User.Create(
            request.UserName,
            request.Email,
            request.Password
        );

        await _userRepository.CreateAsync(user);
        return true;
    }
}
